package com.fast.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fast.exception.BusinessException;
import com.fast.mapper.SysAuthorityMapper;
import com.fast.mapper.SysRoleMapper;
import com.fast.mapper.SysUserMapper;
import com.fast.pojo.dto.SecurityUserDTO;
import com.fast.pojo.entity.SysAuthorityDo;
import com.fast.pojo.entity.SysUserDo;
import com.fast.pojo.vo.SysUserVO;
import com.fast.pojo.vo.UserRouteMetaV0;
import com.fast.pojo.vo.UserRouteVO;
import com.fast.service.SysUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Administrator
 * @description 针对表【sys_user(用户信息表)】的数据库操作Service实现
 * @since 2024-06-23 09:44:12
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDo> implements SysUserService {
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysAuthorityMapper authorityMapper;
    @Resource
    private SysRoleMapper roleMapper;

    /**
     * 根据用户ID获取用户信息
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public SysUserVO getUserInfoById(String userId) {
        SysUserDo sysUserDo = userMapper.getUserInfoById(userId);
        return Convert.convert(SysUserVO.class, sysUserDo);
    }

    /**
     * 根据用户账号获取用户信息
     *
     * @param username 用户名称
     * @return 用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUserDo userInfoByUserName = userMapper.userInfoByUserName(username);
        if (ObjectUtil.isEmpty(userInfoByUserName)) {
            //可以走到认证失败的地方
            throw new BusinessException("账号信息不存在");
        }
        //查询用户权限信息（动态路由树）
        List<SysAuthorityDo> authorityDos = authorityMapper.getAuthoritiesByUserId(userInfoByUserName.getUserId());
        Set<String> backAuthorities = toBackAuthorities(authorityDos);
        List<UserRouteVO> userRoutes = toUserRoutess(authorityDos);
        SecurityUserDTO dto = new SecurityUserDTO();
        dto.setSysUserDo(userInfoByUserName);
        dto.setUserRoutes(userRoutes);
        dto.setBackAuthorities(backAuthorities);
        return dto;
    }

    /**
     * 转换为后端校验全选的路径集合
     */
    private Set<String> toBackAuthorities(List<SysAuthorityDo> authorityDos) {
        if (ObjectUtil.isEmpty(authorityDos)) {
            return new HashSet<>();
        }
        return authorityDos.stream().map(SysAuthorityDo::getRelateBackUris).filter(StrUtil::isNotBlank)
                .flatMap(relateBackUris -> Arrays.stream(relateBackUris.split(String.valueOf(StrUtil.C_COMMA))))
                .filter(StrUtil::isNotBlank).collect(Collectors.toSet());
    }

    /**
     * 转化为前端路由加载的格式
     */
    private List<UserRouteVO> toUserRoutess(List<SysAuthorityDo> authorityDos) {

        List<UserRouteVO> rootNodeList = new ArrayList<>();

        if (ObjectUtil.isEmpty(authorityDos)) {
            return rootNodeList;
        }

        rootNodeList = authorityDos.stream().map(authorityDo -> {
            UserRouteVO userRoute = Convert.convert(UserRouteVO.class, authorityDo);
            UserRouteMetaV0 userRouteMeta = Convert.convert(UserRouteMetaV0.class, authorityDo);
            userRoute.setMeta(userRouteMeta);
            return userRoute;
        }).collect(Collectors.toList());

        return rootNodeList;
    }

}




